<script setup>
//定义变量控制弹窗是否出现
import {onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";
import router from "@/router";

const dialogVisible = ref(false);
//定义变量用来保存弹窗的标题
const dialogTitle = ref();
//定义处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭本弹窗吗?')){
    dialogVisible.value = false;
  }
}
//定义对象用来保存搜索卡片的车位卡详情搜索条件
const searchParkCardForm = ref({
  parkingName:'',
  parkCardName:'',
  status:''
});
//定义数组用来保存车位卡详情表格数据
const userParkCardArr = ref([]);
//定义加载车位卡数据的方法
const loadUserParkCard = ()=>{
  let data = qs.stringify(searchParkCardForm.value)
  console.log(data)
  axios.get(BASE_URL+"/v1/userParkCard/select?"+data).then(response=>{
    if (response.data.code==2000){
      userParkCardArr.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}
//页面一加载完毕,立即调用加载方法
onMounted(()=>{
  loadUserParkCard();
})
const resetSearchForm = ()=>{
  searchParkCardForm.value={}
  loadUserParkCard();
}

// 定义查看车位卡信息的方法
const checkParkCard = (id)=>{

}
const deleteParkCard = (id)=>{
  axios.post(BASE_URL+'/v1/parkCard/delete/'+id).then(response => {
    if (response.data.code==2000){
      ElMessage.success('车位卡删除成功')
      loadUserParkCard()
    }else {
      ElMessage.error(response.data.msg)
    }
  })
}

const addUserParkCard = ()=>{
  //确保每次新增时的标题,且弹窗表单中没有数据
  dialogTitle.value = '新增用户车位卡';
  dialogVisible.value = true;
  saveUserParkCardForm.value = {};
}

const saveUserParkCardForm = ref({
  parkingId:'',
  parkingName:'',
  parkCardName:'',
  userName:'',
  license:'',
  payMethod:'',
  status:''
})

</script>

<template>
  <!-- 用户车位卡页面 -->
  <div style="height:5vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">用户车位卡详情</span>
  </div>

<!--用户车位卡搜索卡片-->
<el-card style="margin: 20px;">
  <el-form :inline="true">
    <el-form-item label="停车场名称:" style="width: 280px;">
      <el-input placeholder="请输入停车场ID" v-model="searchParkCardForm.parkingName" @keydown.enter="loadUserParkCard"></el-input>
    </el-form-item>
    <el-form-item label="车位卡类型:" style="width: 280px;">
      <el-input placeholder="请输入停车场ID" v-model="searchParkCardForm.parkCardName" @keydown.enter="loadUserParkCard"></el-input>
    </el-form-item>
    <el-form-item label="状态:" style="width: 280px;">
      <el-select placeholder="请选择状态" v-model="searchParkCardForm.status">
        <el-option label="有效" value="有效"></el-option>
        <el-option label="失效" value="失效"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button @click="resetSearchForm">重置</el-button>
      <el-button @click="addUserParkCard" type="success">新建</el-button>
      <el-button type="primary" @click="loadUserParkCard">查询</el-button>
    </el-form-item>
  </el-form>
</el-card>
<!--用户车位卡数据表格卡片-->
  <el-card style="margin: 20px;">
    <el-table style="width: 100%" :data="userParkCardArr">
      <el-table-column label="序号" type="index" width="80" align="center"/>
      <el-table-column label="车位卡" prop="parkCardName" align="center"/>
      <el-table-column label="停车场名称" prop="parkingName" align="center"/>
      <el-table-column label="用户" prop="userName" align="center"/>
      <el-table-column label="车牌" prop="license" align="center"/>
      <el-table-column label="状态" prop="status" align="center"/>
      <el-table-column label="生效时间" prop="validDate" align="center"/>
      <el-table-column label="失效时间" prop="comment" align="center"/>
      <el-table-column label="操作" width="200" align="center">
        <template #default="scope">
          <el-button type="success" @click="checkParkCard(scope.row.id)">编辑</el-button>
          <el-button type="danger" @click="deleteParkCard(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>

  <!-- 查看车位卡信息的弹窗 -->
  <el-dialog :title="dialogTitle" v-model="dialogVisible"
             style="width:1000px;padding:40px;" :before-close="handleClose">
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="停车场名称">
            <el-input placeholder="请输入内容" v-model="saveUserParkCardForm.parkingName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input placeholder="请输入内容" v-model="saveUserParkCardForm.userName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="车位卡类型">
            <el-input placeholder="请输入内容" v-model="saveUserParkCardForm.parkCardName"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="车牌号">
            <el-input placeholder="请输入内容" v-model="saveUserParkCardForm.license"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="30">
        <el-col :span="12">
          <el-form-item label="支付方式">
            <el-select placeholder="请选择" v-model="saveUserParkCardForm.payMethod">
              <el-option label="微信" value="微信"></el-option>
              <el-option label="支付宝" value="支付宝"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select placeholder="请选择" v-model="saveUserParkCardForm.status">
              <el-option label="有效" value="有效"></el-option>
              <el-option label="失效" value="失效"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="save">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from "vue";
import axios from "axios";
import { ElMessage } from "element-plus";
import qs from "qs";

const userParkCardArr = ref([]);
const dialogVisible = ref(false);
const dialogTitle = ref("用户车位卡");
const currentRow = ref({
  id: '',
  cardId: '',
  userId: '',
  parkingId: '',
  startDate: '',
  endDate: '',
  status: ''
});
const searchUserCardForm = ref({
  userId: '',
  status: ''
});
// 加载用户车位卡
const loadUserParkCards = async () => {
  try {
    let data = qs.stringify(searchUserCardForm.value);
    const response = await axios.get(`${BASE_URL}/v1/userParkCard/list?${data}`);

    if (response.data.code === 2000) {
      console.log(parkinglots.value);
      userParkCardArr.value = response.data.data.map(card => {
        const parking = parkinglots.value.find(p => p.id === card.parkingId);
        // console.log("parking666");
        // console.log(parking);
        return {
          ...card,
          parkingName: parking ? parking.name : '未知'
        };
      });
    } else {
      throw new Error(response.data.msg);
    }
  } catch (error) {
    ElMessage.error(error.message || '加载用户车位卡失败');
  }
};

// 新建用户车位卡
const newUserParkCard = () => {
  currentRow.value = {
    cardId: '',
    userId: '',
    parkingId: '',
    startDate: '',
    endDate: '',
    status: ''
  };
  dialogVisible.value = true;
};

// 编辑用户车位卡
const checkUserParkCard = (row) => {
  currentRow.value = { ...row };
  dialogVisible.value = true;
};
const formatDateToLocal = (date) => {
  let d = new Date(date);
  return d.getFullYear() + '-' +
      ('0' + (d.getMonth() + 1)).slice(-2) + '-' +
      ('0' + d.getDate()).slice(-2) + ' ' +
      ('0' + d.getHours()).slice(-2) + ':' +
      ('0' + d.getMinutes()).slice(-2) + ':' +
      ('0' + d.getSeconds()).slice(-2);
};
// 保存用户车位卡
const handleSave = () => {
  currentRow.value.startDate = formatDateToLocal(currentRow.value.startDate);
  currentRow.value.endDate = formatDateToLocal(currentRow.value.endDate);
  let data = JSON.stringify(currentRow.value);
  console.log(data);
  console.log(currentRow.value.id);
  if (currentRow.value.id) {
    axios(
    {
      method: 'post',
          url: BASE_URL + '/v1/userParkCard/update',
        data: data,
        headers: {
      'Content-Type': 'application/json;charset=UTF-8'
    }
    }

    ).then(response => {
      if (response.data.code === 2000) {
        ElMessage.success('用户车位卡更新成功');
        loadUserParkCards();
        dialogVisible.value = false;
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  } else {
    axios.post(BASE_URL + '/v1/userParkCard/save', data).then(response => {
      if (response.data.code === 2000) {
        ElMessage.success('用户车位卡创建成功');
        loadUserParkCards();
        dialogVisible.value = false;
      } else {
        ElMessage.error(response.data.msg);
      }
    });
  }
};

// 删除用户车位卡
const deleteUserParkCard = (id) => {
  axios.post(BASE_URL + '/v1/userParkCard/delete/' + id).then(response => {
    if (response.data.code === 2000) {
      ElMessage.success('用户车位卡删除成功');
      loadUserParkCards();
    } else {
      ElMessage.error(response.data.msg);
    }
  });
};

// 重置搜索表单
const resetSearchForm = () => {
  searchUserCardForm.value = {};
  loadUserParkCards();
};

// 页面加载时，加载数据
onMounted(() => {
  getParkinglots();
  loadUserParkCards();

});
const options = [
];
//停车场数组
const parkinglots = ref([]);
const getParkinglots = ()=>{
  axios.get(BASE_URL+'/parklot/list')
      .then((response)=>{//回调函数,服务器响应后执行此处代码
        /*response是响应对象,我们可以从response.data中获取服务器给的响应数据*/
        //console.log("response");
        console.log(response.data);//{code:2000,msg:'OK',data:null}
        //根据状态码判断是否获取停车场列表成功,进行不同的处理
        if(response.data.code==2000){/*获取停车场列表成功*/
          parkinglots.value = response.data.data;
          console.log(parkinglots.value);
          //将停车场数组赋值到options数组中
          options.splice(0,options.length);
          for(let i=0;i<parkinglots.value.length;i++){
            options.push({value:parkinglots.value[i].id,label:parkinglots.value[i].name});
            console.log(options);
          }
        }else{/*获取停车场列表失败*/
          ElMessage.error(response.data.msg);
        }
      })
}
</script>

<style scoped>
/* 自定义样式 */
</style>
